package com.tally.server.utils;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * @Author: sy
 * @Date: 2020/12/13 13:29
 * @Description:
 */
public class DateUtil {
    public static Date localDate2Date(LocalDate localDate){
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

    public static Calendar getCalendar(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public static int lastDayOf(int year,int month){
        int day;
        switch (month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                if(isLeap(year)){
                    day = 29;
                }else{
                    day = 28;
                }
                break;
            default:
                day = 30;
        }
        return day;
    }

    private static boolean isLeap(int year){
        return year%4 == 0 && year%100 != 0 || year % 400 == 0;
    }

    public static List<Date> dateList(Date start, Date end) {
        List<Date> result = new ArrayList<Date>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
//        tempStart.add(Calendar.DAY_OF_YEAR, 1);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        do {
            result.add(tempStart.getTime());
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        } while (!tempStart.after(tempEnd));
        return result;
    }

    public static Set<Date> dateMonthList(Date start, Date end) {
        Set<Date> result = new HashSet<>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
//        tempStart.add(Calendar.DAY_OF_YEAR, 1);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        do {
            result.add(tempStart.getTime());
            tempStart.add(Calendar.MONTH, 1);
        } while (tempStart.before(tempEnd));
        result.add(end);
        return result;
    }

    public static void main(String[] args) {
        LocalDate localDate = LocalDate.of(2020,2,23);
        System.out.println(localDate2Date(localDate));
    }
}
